//
//  UserAccountViewModel.swift
//  weibo
//
//  Created by 王、小胜 on 16/7/27.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit

class UserAccountViewModel {
    
    ///单例：避免重复从沙盒加载归档文件1
    static let sharedUserAccount = UserAccountViewModel()

    
    ///用户模型
    var account:UserAccount?
    
    ///返回有效的token
    var accessToken: String? {
        //如果 token 没有过期，返回token中的属性
        if !isExpired {
            return account?.access_token
        }
        return nil
    }
    
    ///用户登录标记
    var userLogin:Bool {
        //判断token是否有值
        //判断是否过期
        
        return account?.access_token != nil && !isExpired
    }
    
    ///用户头像
    var avatarUrl: NSURL {
        return NSURL(string: account?.avatar_large ?? "")!
    }
    ///归档保存路径
    private var accountPath: String {
        //1.保存路径
       let  path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask, true).last!
        
        return (path as NSString).stringByAppendingPathComponent("account.plist")
    }
    
    
    ///判断用户是否过期
    private var isExpired:Bool {
        
        //自己写日期用来测试逻辑是否正确
        //account?.expiresDate = NSDate(timeIntervalSinceNow: -3600)
        
        //判断用户是否过期，与当前系统时间进行比较
        
        if account?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            //到这里一定进行过比较
            return false
        }
        
        //过期返回
        return true
    }
    
    ///构造函数
    private init() {
        //从沙河解析数据
        account =  NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
        
        //判断token是否过期
        if isExpired {
            print("已经过期")
            
            //如果过期，清空account数据
            account = nil
        }
        print(account)
    }
}


//MARK : - 用户相关的网络方法
extension UserAccountViewModel {
    
    func loadAccessToken(code:String, finished: (isSuccessed: Bool) ->()) {
        
        NetworkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
            //1.判断错误
            if error != nil {
                print("出错了")
                
                return
            }
            
            //2.输出结果
            print(result)
            
            self.account = UserAccount(dict: result as![String: AnyObject])
            
            self.loadUserInfo(self.account!,finished: finished)
        }
    }
    
    //用户信息
    private func loadUserInfo(account: UserAccount, finished: (isSuccessed: Bool) ->()){
        
        NetworkTools.sharedTools.loadUserInfo(account.uid!) { (result, error) -> () in
            
            if error != nil {
                print("加载用户信息出错")
                
                finished(isSuccessed: false)
                return
            }
            
            //做两个判断
            //1.result一定有内容
            //2.一定是字典
            
            guard let dict = result as? [String :AnyObject] else {
                print("格式错误")
                
                finished(isSuccessed: false)
                return
            }
            
            //dict一定是有值的字典
            
            ///保存用户信息
            
            account.screen_name = dict["screen_name"] as? String
            account.avatar_large = dict["avatar_large"] as? String
            
           
            //保存对象
          NSKeyedArchiver.archiveRootObject(account, toFile: self.accountPath)
            print(self.accountPath)
            
            finished(isSuccessed: true)
            
        }
    }

    
}






